from rest_framework import viewsets, status
from rest_framework.decorators import action
from django.contrib.auth.hashers import make_password
from rest_framework.authtoken.models import Token
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.authentication import TokenAuthentication

from users.serializer.forms.login_forms import UserLoginForms
from users.serializer.forms.register_forms import UserRegisterForms
from users.service.user_service import AuthService
from users.serializer.serializers import UserProfileSerializer, UserUpdateSerializer
from weiwenhai_Oj.deprecated.handle_exceptions import handle_exceptions
from weiwenhai_Oj.utils.global_functions import Response


class UserController(viewsets.ModelViewSet):
    authentication_classes = [TokenAuthentication]
    permission_classes = [IsAuthenticated]
    auth_service = AuthService()

    @action(methods=['post'], detail=False, permission_classes=[AllowAny])
    @handle_exceptions
    def register(self, request):
        """
        用户注册
        """
        forms = UserRegisterForms(data=request.data)
        if not forms.is_valid():
            return Response({"msg": "注册失败，请检查输入信息"}, status=status.HTTP_400_BAD_REQUEST)

        user_data = forms.validated_data
        user_data['password'] = make_password(user_data['password'])  # 密码加密
        token = self.auth_service.register(user_data)

        return Response(data={'token': token}, msg="注册成功", status=status.HTTP_201_CREATED)

    @action(methods=['post'], detail=False, permission_classes=[AllowAny])
    @handle_exceptions
    def login(self, request):
        """
        用户登录
        """
        forms = UserLoginForms(data=request.data)
        if not forms.is_valid():
            return Response(msg="登录失败，请检查输入信息", status=status.HTTP_400_BAD_REQUEST)

        account = forms.validated_data.get('username')
        password = forms.validated_data.get('password')
        token = self.auth_service.login_in(account, password)

        return Response(data={'token': token}, msg="登录成功", status=status.HTTP_200_OK)

    @action(methods=['get'], detail=False)
    @handle_exceptions
    def profile(self, request):
        """
        获取用户个人信息
        """
        serializer = UserProfileSerializer(request.user)
        return Response(data=serializer.data, msg="获取成功", status=status.HTTP_200_OK)

    @action(methods=['put'], detail=False)
    @handle_exceptions
    def update_profile(self, request):
        """
        更新用户个人信息
        """
        serializer = UserUpdateSerializer(request.user, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            # 返回更新后的完整用户信息
            profile_serializer = UserProfileSerializer(request.user)
            return Response(data=profile_serializer.data, msg="更新成功", status=status.HTTP_200_OK)
        return Response(msg="更新失败，请检查输入信息", status=status.HTTP_400_BAD_REQUEST)

    @action(methods=['post'], detail=False)
    @handle_exceptions
    def change_password(self, request):
        """
        修改密码
        """
        old_password = request.data.get('old_password')
        new_password = request.data.get('new_password')

        if not old_password or not new_password:
            return Response(msg="请提供旧密码和新密码", status=status.HTTP_400_BAD_REQUEST)

        # 验证旧密码
        if not request.user.check_password(old_password):
            return Response(msg="旧密码不正确", status=status.HTTP_400_BAD_REQUEST)

        # 设置新密码
        request.user.set_password(new_password)
        request.user.save()

        return Response(msg="密码修改成功", status=status.HTTP_200_OK)

    @action(methods=['post'], detail=False)
    @handle_exceptions
    def logout(self, request):
        """
        用户退出登录
        """
        if request.user.is_authenticated:
            Token.objects.filter(user=request.user).delete()
            return Response(msg="退出成功", status=status.HTTP_200_OK)
        return Response(msg="用户未登录", status=status.HTTP_400_BAD_REQUEST)